package com.bb.blog.code.mybatis.mapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


public class MapperXProxy<T> implements InvocationHandler, Serializable {
    private final Map<Method, MapperXMethod> methodCache;
    Logger logger = LoggerFactory.getLogger(MapperXProxy.class);
    private Class<T> mapperInterface;

    public MapperXProxy(Class<T> clazz) {
        this.mapperInterface = clazz;
        this.methodCache = new HashMap<>();

    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperXMethod mapperXMethod = cacahedMapperMethod(method);
        logger.info("执行了 -------> " + mapperInterface.toString() + "#### " + method.getName());
        return mapperXMethod.execute();

    }

    private MapperXMethod cacahedMapperMethod(Method method) {
        return methodCache.computeIfAbsent(method, k -> new MapperXMethod(mapperInterface, method));
    }

    private class MapperXMethod {
        private String content;

        public MapperXMethod(Class<?> mapperInterface, Method method) {
            this.content = MapperXRegistry.resolveMapperContent(mapperInterface, method.getName());
        }

        public Object execute() {
            logger.info(content);
            return content;
        }
    }
}
